import * as XLSX from "xlsx";


// 经过评论反馈优化
function getCellWidth(value) {
    // 判断是否为null或undefined
    if (value == null) {
        return 10;
    } else if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
        // 中文的长度
        const chineseLength = value.match(/[\u4e00-\u9fa5]/g).length;
        // 其他不是中文的长度
        const otherLength = value.length - chineseLength;
        return chineseLength * 2.1 + otherLength * 1.1;
    } else {
        return value.toString().length * 1.1;
        /* 另一种方案
        value = value.toString()
        return value.replace(/[\u0391-\uFFE5]/g, 'aa').length
        */
    }
}



/**
 * @description: 
 * @param {*} json：服务端发过来的数据
 * @param {*} name：导出Excel文件名字
 * @param {*} titleArr：导出Excel表头
 * @param {*} sheetName：导出sheetName名字
 */
export function exportExcel(json, name, titleArr, sheetName = 'sheet1') {
    /* convert state to workbook */
    let data = new Array();

    data.push(titleArr.map(item => item.label))

    for (const key in json) {
        let item = []
        for (const key2 in titleArr) {
            item.push(json[key][titleArr[key2].key])
        }
        data.push(item)
    }


    const ws = XLSX.utils.aoa_to_sheet(data)
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, sheetName);


    XLSX.writeFile(wb, name + '.xlsx');
}



/**
 * @description: 将excel表格转换为JSON
 * @param {*} file：需要转换的文件
 * @param {*} sheetNameList：需要转换的sheet
 * @return {*}
 */
export function excelToJson(file, sheetNameList) {
    if (!file) {
        return false
    } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        return false
    }


    return new Promise((resolve, reject) => {
        const fileReader = new FileReader()
        let fileData = {}
        fileReader.readAsArrayBuffer(file)

        fileReader.onload = function (event) {
            const data = event.target.result
            const workbook = XLSX.read(data, { type: 'binary' })
            if (workbook.SheetNames.length > 0) {

                // 未指定读取的sheet的时候，默认读取全部的sheet
                const _sheetNameList = sheetNameList ? sheetNameList : workbook.SheetNames

                for (let index = 0; index < _sheetNameList.length; index++) {
                    const sheetName = _sheetNameList[index]
                    if (_sheetNameList.includes(sheetName)) {
                        fileData[sheetName] = []
                        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName])
                        fileData[sheetName] = ws
                    }
                }
            }
            resolve(fileData)
        }
    })

}